package chat.user.servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import chat.user.domain.User;
import chat.user.service.UserException;
import chat.user.service.UserService;



@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	UserService userService = new UserService();
  

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-type","text/html;charset=UTF-8");
		
		
	}


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("content-type","text/html;charset=UTF-8");
		
		User form = new User();
		form.setUsername(request.getParameter("username"));
		form.setPassword(request.getParameter("password"));
		
		
		try
		{
			userService.regist(form);
			Map<String,String> msgMap = new HashMap<String,String>();
			msgMap.put("title", "注册成功");
			msgMap.put("desc", "现在去登陆吧!");
			msgMap.put("type", "登陆");
			msgMap.put("url", "/view/login.jsp");
		
			request.setAttribute("msg", msgMap);
			request.getRequestDispatcher("/view/msg.jsp").forward(request, response);
		}
		catch(UserException e)
		{
			request.setAttribute("msg",e.getMessage());
			request.getRequestDispatcher("/view/regist.jsp").forward(request, response);
		}
	}

}
